package zhihuilan.controlle.wechatMini;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.catalina.startup.Tool;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import zhihuilan.common.Response;
import zhihuilan.common.WxMiniResponse;
import zhihuilan.common.enums.ResultEnum;
import zhihuilan.common.utils.AliyunUtils;
import zhihuilan.common.utils.RedisCache;
import zhihuilan.common.utils.ToolsUtils;
import zhihuilan.config.StaticFiledConfig;
import zhihuilan.controlle.BasicController;
import zhihuilan.dto.MyPcdDto;
import zhihuilan.dto.MyStaffAddressDto;
import zhihuilan.entity.MyPcd;
import zhihuilan.entity.MyStaffAddress;
import zhihuilan.params.StaticParam;
import zhihuilan.service.MyPcdService;
import zhihuilan.service.MyStaffAddressService;
import zhihuilan.service.ToolService;

import javax.annotation.Resource;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static zhihuilan.common.utils.ToolsUtils.verifymsg;


@Slf4j
@RestController
@RequestMapping("/app/Tool")
public class ToolController  extends BasicController {

    @Resource
    private ToolService toolService;

    @Resource
    private MyStaffAddressService myStaffAddressService;


    /**
     * 发送手机信息
     * mobile 手机号码
     * code||name 验证码||姓名
     * type 1=通过信息  2=未通过信息  3=验证码
     *
     * */
    @PostMapping("/sendsms")
    public WxMiniResponse sendsms(@RequestBody JSONObject jsonObject) throws Exception {
        if(StringUtils.isEmpty(jsonObject.getString("mobile"))){
            return WxMiniResponse.error( 1008 ,"请输入手机号");
        }
        Map map =(Map)jsonObject;
        return toolService.sendsms(map);

    }

    /**
     * 根据经纬度获取地址
     * lat 经度
     * lng 纬度
     *
     * */
    @PostMapping("/getLng2Address")
    public WxMiniResponse getLng2Address(@RequestBody JSONObject jsonObject){
        return toolService.getLng2Address(jsonObject);
    }

    /**
     * 根据城市代码和等级获取城市
     * districtid 城市代码
     * level 等级
     *
     * */
    @PostMapping("/getcitylist2")
    public WxMiniResponse getcitylist2(@RequestBody JSONObject jsonObject)  {
        return toolService.getcitylist2(jsonObject);
    }


    /**
     * 获取定位城市
     * @apiParam {string}  lng 经度
     * @apiParam {string}  lat 纬度
     */
    @PostMapping("/getcity")
    public WxMiniResponse getcity(@RequestBody JSONObject jsonObject) throws UnknownHostException, WxErrorException {
        return toolService.getcity(jsonObject);
    }

    /**
     * 获取城市列表
     * @apiParam {string} keyword 搜索关键字
     */
    @PostMapping("/getcitylist")
    public WxMiniResponse getcitylist(@RequestBody JSONObject jsonObject)
    {
        return toolService.getcitylist(jsonObject);
    }

    /**
     * 获取行业分类列表；
     * @apiParam {int} type 1=小程序
     * @apiParam {int} level 等级
     */
    @PostMapping("/getCategoryBox")
    public WxMiniResponse getCategoryBox(@RequestBody JSONObject jsonObject)
    {
        return toolService.getCategoryBox(jsonObject);
    }

    /**
     * @api {Post} /Tool/setStaffInfoAddress 修改用户地址
     * @apiParam {string}  guid 用户标识
     * @apiParam {int}  districtid   地址code：510101
     * @apiParam {string}  region   地址： 四川，成都，天府区
     *  @apiParam {string}  address   详细地址
     */
    @PostMapping("/setStaffInfoAddress")
    public WxMiniResponse setStaffInfoAddress(@RequestBody MyStaffAddress myStaffAddress)
    {
//        if (ObjectUtils.isEmpty(myStaffAddress.getGuid())) {
//            return WxMiniResponse.error(ResultEnum.ERROR.getKey(), "缺少code", "缺少code！");
//        }
        if (!this.isCheckLogin(myStaffAddress.getGuid())) {
                //如果用户未登陆，提示用户未登，并且返回未登陆的枚举编码；
                return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }
        myStaffAddress.setStaffId(currentStaff.getId());
        MyStaffAddress myStaffAddress1 =  myStaffAddressService.getStaffInfoAddressByStaffId(currentStaff.getId());
        if(myStaffAddress1==null){
            Integer d = myStaffAddressService.insertStaffInfoAddress(myStaffAddress);
            if(d.equals(1)){
                return WxMiniResponse.ok("提交成功！");
            }
            return  WxMiniResponse.ok("提交失败！");

        }else {
            Integer d = myStaffAddressService.updateStaffInfoAddress(myStaffAddress);
            if(d.equals(1)){
                return WxMiniResponse.ok("提交成功！");
            }
            return  WxMiniResponse.ok("提交失败！");
        }
    }

    @Autowired
    MyPcdService myPcdService;

    /**
     * @api {Post} /Tool/getStaffInfoAddress 获取用户地址
     * @apiParam {string}  guid 用户标识
     */
    @PostMapping("/getStaffInfoAddress")
    public WxMiniResponse getStaffInfoAddress(@RequestBody MyStaffAddress myStaffAddress){
        if (!this.isCheckLogin(myStaffAddress.getGuid())) {
            //如果用户未登陆，提示用户未登，并且返回未登陆的枚举编码；
          //  return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }else {
            MyStaffAddress myStaffAddress1 = myStaffAddressService.getStaffInfoAddressByStaffId(currentStaff.getId());
            if(myStaffAddress1!=null){
                MyPcd myPcd =   myPcdService.selectMyPcdByCode(Integer.parseInt(myStaffAddress1.getDistrictid().substring(0,2)));
                MyPcdDto myPcdDto = new MyPcdDto();
                BeanUtils.copyProperties(myPcd,myPcdDto);
                return WxMiniResponse.ok(myPcdDto);
            }
        }

        return  WxMiniResponse.ok();
    }

    /**
     * @api {Post} /Tool/kouPicture 获取商家商品列表
     * @apiVersion 1.0.0
     * @apiName kouPicture
     * @apiGroup Tool
     * @apiParam {string}  guid 用户标识
     * @apiParam {string}  url   图片地址
     *
     */
    @Resource
    private StaticFiledConfig myStaticConfig;


    @Autowired
    RedisCache redisCache;

    @PostMapping("/aliStsToken")
    public WxMiniResponse  aliStsToken(@RequestBody StaticParam staticParam) {
        if (!this.isCheckLogin(staticParam.getGuid())) {
            //如果用户未登陆，提示用户未登，并且返回未登陆的枚举编码；
      //        return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }
        AliyunUtils aliyunUtils = new AliyunUtils();
        String map = redisCache.getCacheObject("aliyunSts");
        if(ObjectUtils.isEmpty(map)){
            map = aliyunUtils.stsAliyun(myStaticConfig.getAccessKeyId(),myStaticConfig.getAccessKeySecret(),myStaticConfig.getRamRoleArn());
            redisCache.setCacheObject("aliyunSts",map,110, TimeUnit.MINUTES);
        }
        return WxMiniResponse.ok(JSONObject.parseObject(map));
    }

    @PostMapping("/kouPicture")
    public WxMiniResponse  kouPicture(@RequestBody StaticParam staticParam) {
        if (!this.isCheckLogin(staticParam.getGuid())) {
            //如果用户未登陆，提示用户未登，并且返回未登陆的枚举编码；
              return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }
        try {
            AliyunUtils aliyunUtils = new AliyunUtils();
            // print_r($ff['imageUrl']);
            String jsonObject = aliyunUtils.segmentHDCommonImage(staticParam.getUrl(),myStaticConfig.getAccessKeyId(),myStaticConfig.getAccessKeySecret());
//            System.out.println(jsonObject);
            return WxMiniResponse.ok(jsonObject);
            //  echo Utils::toJSONString($resp);
        } catch (Exception e) {
            return  WxMiniResponse.error(2012,e.getMessage());
        }
    }

    /**
     * @api {GET} /Tool/getAsyncJobResult 获取阿里异步信息
     * @apiVersion 1.0.0
     * @apiName String guid
     * @apiGroup String code
     */
    @PostMapping("/getAsyncJobResult")
    public WxMiniResponse  getAsyncJobResult(@RequestBody StaticParam staticParam) {
        if (!this.isCheckLogin(staticParam.getGuid())) {
            //如果用户未登陆，提示用户未登，并且返回未登陆的枚举编码；
            return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }
        try {
            AliyunUtils aliyunUtils = new AliyunUtils();
            JSONObject jsonObject = aliyunUtils.GetAsyncJobResult(staticParam.getCode(),myStaticConfig.getAccessKeyId(),myStaticConfig.getAccessKeySecret());
            jsonObject.put("imageUrl", jsonObject.getString("imageUrl").replaceAll("http:","https:"));
            return WxMiniResponse.ok(jsonObject);
        } catch (Exception e) {
            return  WxMiniResponse.ok();
        }
    }


    /**
     * @api {GET} /Tool/getcitydlist 获取城市(市)列表
     * @apiVersion 1.0.0
     * @apiName getcitydlist
     * @apiGroup Tool
     */
    @PostMapping("/getcitydlist")
    public WxMiniResponse  getcitydlist(String keyword) {
        List<MyPcd> hotList = myPcdService.selectHotList(keyword);
        List<String> enList = myPcdService.selectEnList(keyword);
        List<Map<String,Object>> cityList = myPcdService.selectCityList(keyword,enList);
        Map<String,Object> map = new HashMap<>();
        map.put("hotlist",hotList);
        map.put("enlist",enList);
        map.put("citylist",cityList);
        return WxMiniResponse.ok(map);
    }

}
